//import {ToastMessager, MessagerLevel} from './messager.js'

const RequestCode = Object.freeze({
    GET_ALL_META_DATA: 2,
    ADD_META_DATA: 3,
    UPDATE_META_DATA: 4,
    DELETE_META_DATA: 5,
    GET_ARTICLE_DATA: 6,
    ADD_SECTION_DATA: 7,
    UPDATE_SECTION_DATA: 8,
    MOVE_SECTION_DATA: 9,
    DELETE_SECTION_DATA: 10,
    CLIENT_STATUS: 998,
    ARCHIVE: 999,

    HEART_BEAT: 0,
    SAVE: 111,
    SAVE_AND_EXIT: 222,
    DELETE: 10,
    CANCEL: 20,
    LOGIN: 100,
    UPLOAD: 1000,
    ACTION_CONFIRMED: 5000,
    FILE_EXIST: 5100,
});

const _jsonHeader = new Headers();
_jsonHeader.append('Content-Type', 'application/json');

const _formHeader = new Headers();
_formHeader.append('Content-Type', 'multipart/form-data');

async function _Post(code, data, headers) {
    headers = headers ?? _jsonHeader;
    const body = JSON.stringify({code, data});
    const response = await fetch('/service', {
        method: 'POST',
        headers,
        body,
    });
    return response.json()
        .then(cbData => {
            if (cbData.code < 0) {
                //ToastMessager.Show(cbData.msg, MessagerLevel.ERROR);
                return Promise.reject();
            } else {
                return cbData.data;
            }
        }, (error) => {
            //ToastMessager.Show(`net error:\n ${error}`, MessagerLevel.ERROR);
            return Promise.reject();
        });
}

export function proxy_GetPagePropertyList() {
    return _Post(RequestCode.GET_ALL_META_DATA);
}

export function proxy_AddPageProperty(jsonObj) {
    return _Post(RequestCode.ADD_META_DATA, {data: jsonObj});
}

export function proxy_UpdatePageProperty(jsonObj) {
    return _Post(RequestCode.UPDATE_META_DATA, {data: jsonObj});
}

export function proxy_DeletePageProperty(SUID) {
    return _Post(RequestCode.DELETE_META_DATA, {SUID});
}

export function proxy_GetPageContent(SUID) {
    return _Post(RequestCode.GET_ARTICLE_DATA, {SUID});
}

export function proxy_AddWidgetContent(SUID, index, sectionData) {
    return _Post(RequestCode.ADD_SECTION_DATA, {SUID, index, data: sectionData});
}

export function proxy_UpdateWidgetContent(PID, sectionData) {
    return _Post(RequestCode.UPDATE_SECTION_DATA, {PID, data: sectionData});
}

export function proxy_MoveWidgetContent(SUID, SID, index) {
    return _Post(RequestCode.MOVE_SECTION_DATA, {SUID, SID, index});
}

export function proxy_DeleteWidgetContent(SUID, SID) {
    return _Post(RequestCode.DELETE_SECTION_DATA, {SUID, SID});
}

export function proxy_Archive() {
    return _Post(RequestCode.ARCHIVE);
}

export function proxy_Log() {
    return _Post(RequestCode.CLIENT_STATUS);
}

